package com.weijian.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weijian.entity.VideoInfo;
import com.weijian.mapper.VideoInfoMapper;
import com.weijian.service.VideoInfoService;
import com.weijian.service.MinIOService;
import com.weijian.utils.FileValidationUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 视频信息Service实现类
 * 继承ServiceImpl，使用MyBatis-Plus提供的Service实现
 */
@Slf4j
@Service
public class VideoInfoServiceImpl extends ServiceImpl<VideoInfoMapper, VideoInfo> implements VideoInfoService {

    @Autowired
    private MinIOService minIOService;
    
    @Autowired
    private FileValidationUtils fileValidationUtils;

    @Override
    @Transactional
    public VideoInfo uploadVideo(MultipartFile file) {
        log.info("开始上传视频文件: {}", file.getOriginalFilename());
        
        // 验证文件
        String validationError = fileValidationUtils.getValidationError(file);
        if (validationError != null) {
            throw new IllegalArgumentException(validationError);
        }
        
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + fileExtension;
            
            // 生成存储路径（按日期分组）
            String filePath = "videos/" + LocalDateTime.now().getYear() + "/" + 
                             LocalDateTime.now().getMonthValue() + "/" + uniqueFileName;
            
            // 上传到MinIO
            String objectUrl = minIOService.uploadFile(file, filePath);
            
            // 创建视频信息记录
            VideoInfo videoInfo = new VideoInfo();
            videoInfo.setTitle(originalFilename.substring(0, originalFilename.lastIndexOf(".")));
            videoInfo.setFileName(originalFilename);
            videoInfo.setFilePath(filePath);
            videoInfo.setFileSize(file.getSize());
            videoInfo.setDuration(0); // TODO: 后续集成FFmpeg获取时长
            videoInfo.setUploadTime(LocalDateTime.now());
            
            // 保存到数据库
            this.save(videoInfo);
            
            log.info("视频上传成功，ID: {}, 文件名: {}", videoInfo.getId(), originalFilename);
            return videoInfo;
            
        } catch (Exception e) {
            log.error("视频上传失败: {}", e.getMessage(), e);
            throw new RuntimeException("视频上传失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<VideoInfo> getVideoPage(Integer pageNum, Integer pageSize) {
        log.info("查询视频列表，页码: {}, 每页数量: {}", pageNum, pageSize);
        
        Page<VideoInfo> page = new Page<>(pageNum, pageSize);
        return this.page(page, null);
    }

    @Override
    @Transactional
    public boolean deleteVideo(Long id) {
        log.info("开始删除视频，ID: {}", id);
        
        try {
            VideoInfo videoInfo = this.getById(id);
            if (videoInfo == null) {
                throw new IllegalArgumentException("视频不存在，ID: " + id);
            }
            
            // 删除MinIO中的文件
            minIOService.deleteFile(videoInfo.getFilePath());
            
            // 删除缩略图（如果存在）
            if (videoInfo.getThumbnailPath() != null) {
                minIOService.deleteFile(videoInfo.getThumbnailPath());
            }
            
            // 删除数据库记录
            boolean removed = this.removeById(id);
            
            if (removed) {
                log.info("视频删除成功，ID: {}", id);
            } else {
                log.warn("视频删除失败，ID: {}", id);
            }
            
            return removed;
            
        } catch (Exception e) {
            log.error("视频删除失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            throw new RuntimeException("视频删除失败: " + e.getMessage());
        }
    }

    @Override
    public boolean generateThumbnail(String videoPath, String outputPath) {
        // TODO: 集成FFmpeg生成缩略图
        log.info("生成缩略图功能待实现，视频路径: {}, 输出路径: {}", videoPath, outputPath);
        return false;
    }
}